package fs.ls.gs.Utils;

import java.sql.*;

/**
 * @Auther: zhezhe
 * @Date: 2018/9/1416:44
 * @Description:
 */
public class DbUtils {


    /**
     * JDBC驱动名及数据库URL
     */
    public static final String JDBC_DRIVER = "com.mysql.jdbc.Driver";
    public static final String URL = "jdbc:mysql://localhost:3306/goods?useUnicode=true&characterEncoding=utf8&serverTimezone=UTC";

    /**
     * 数据库的用户名与密码，需要根据自己的设置
     */

    public static final String USER = "root";
    public static final String PASSWORD = "root";



    /**
     * 单例模式
     */
    private static Connection conn = null;



    /**
     * 私有化构造器
     */
    private DbUtils(){}

    public static Connection getConnection(){
        if (conn == null){
            try {
                //加载驱动程序
                Class.forName(JDBC_DRIVER);
                //获得数据库连接
                conn = DriverManager.getConnection(URL,USER,PASSWORD);
            } catch (ClassNotFoundException e) {
                e.printStackTrace();
            } catch (SQLException e) {
                e.printStackTrace();
            }
        }

        return conn;
    }


    /**
     * 关闭连接对象
     * @param con
     */
    public static void closeConnection(Connection con){
        if(con != null){
            try {
                con.close();
            } catch (SQLException e) {
                e.printStackTrace();
            }
        }
    }


    /**
     * 关闭预处理对象语句
     * @param pst
     */
    public static void closepp(PreparedStatement pst){
        if (pst != null){
            try {
                pst.close();
            } catch (SQLException e) {
                e.printStackTrace();
            }
        }
    }
    /**
     * 关闭处理语句对象
     */

    public static void closeStatement(Statement stt) {
        if (stt != null){
            try {
                stt.close();
            } catch (SQLException e) {
                e.printStackTrace();
            }
        }
    }

}
